package com.linden.std.Utils;

import com.linden.std.domain.vo.UserVO;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 用户上下文工具类
 */
public class UserContextUtil {
    
    private static final ThreadLocal<UserVO> USER_HOLDER = new ThreadLocal<>();

    /**
     * 设置用户信息
     */
    public static void setUser(UserVO user) {
        USER_HOLDER.set(user);

        // 注册请求结束时的清理回调
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                attributes.registerDestructionCallback("userContext", () -> {
                    removeUser();
                }, RequestAttributes.SCOPE_REQUEST);
            }
        } catch (Exception e) {
            // 忽略异常，使用默认的ThreadLocal清理机制
        }
    }
    /**
     * 获取用户信息
     */
    public static UserVO getUser() {
        return USER_HOLDER.get();
    }
    
    /**
     * 清除用户信息
     */
    public static void removeUser() {
        USER_HOLDER.remove();
    }
    
    /**
     * 获取用户ID
     */
    public static Long getUserId() {
        UserVO user = getUser();
        return user != null ? user.getUserId() : null;
    }
    
    /**
     * 获取用户名
     */
    public static String getUsername() {
        UserVO user = getUser();
        return user != null ? user.getAccount() : null;
    }
}